package dao

import (
	"fmt"
	"gitee.com/blueskyxi2006/sql-metrics/logger"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gopkg.in/ini.v1"
)

var (
	DB *gorm.DB
)

func InitMySQL(cfg *ini.File) (err error) {
	user := cfg.Section("database").Key("user").String()
	password := cfg.Section("database").Key("password").String()
	host := cfg.Section("database").Key("host").String()
	port := cfg.Section("database").Key("port").String()
	db := cfg.Section("database").Key("db").String()
	//DB, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")

	//dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
	//	user, password, host, port, db)

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", user, password, host, port, db, "utf8&parseTime=True&loc=Local")

	logger.Info(dsn)
	//dsn = "root:123456@/cms?charset=utf8&parseTime=True&loc=Local"
	DB, err = gorm.Open("mysql", dsn)
	if err != nil {
		logger.Error(err)
		return
	}
	return DB.DB().Ping()
}

func Close() {
	DB.Close()
}